﻿using JYH.Business;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Timers;
using System.Windows.Forms;

namespace JYH.ERP.Smart
{
    public class SynchronousData
    {

        private readonly System.Timers.Timer _timer;
        public string MethodName  { get; set; }

        /// <summary>
        /// 物料信息同步对象
        /// </summary>
        /// <param name="intervalHours">同步频率 以分钟为单位</param>
        public SynchronousData(double intervalHours,string sMethodName)
        {
            MethodName = sMethodName;

            // 设置定时器（以小时为单位）
            _timer = new System.Timers.Timer(intervalHours * 60 * 1000);
            _timer.Elapsed += CleanOldFiles;
            _timer.AutoReset = true;
            _timer.Enabled = true;
            // 首次启动时立即执行一次
            CleanOldFiles(null, null);
        }

        private async void CleanOldFiles(object sender, ElapsedEventArgs e)
        {
            try
            {
                await Task.Run(() => Synchronous(MethodName));
            }
            catch
            {

            }
        }

        public void Start() => _timer.Start();
        public void Stop() => _timer.Stop();


        /// <summary>
        /// 数据同步
        /// </summary>
        /// <returns></returns>
        private async Task Synchronous(string MethodName)
        {
            string Msg = string.Empty;
            try
            {
                string Date = DateTime.Now.ToString("yyyy-MM-dd");
                string NO = "";
                object[] args = { Date, NO, Msg };
                bool res =  SyncData.SynchronousData("", MethodName, args, out Msg);
                if (!res)
                {
                    string Path = Application.StartupPath + @"\\Log\\";
                    if (!Directory.Exists(Path))
                    {
                        Directory.CreateDirectory(Path);
                    }
                    Path += "\\" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".txt";
                    File.WriteAllText(Path, Msg);
                }
            }
            catch (Exception ex)
            {

                string Path = Application.StartupPath + @"\\Log\\";
                if (!Directory.Exists(Path))
                {
                    Directory.CreateDirectory(Path);
                }
                Path += "\\" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".txt";
                File.WriteAllText(Path, ex.ToString());
            }
        }
    }
}
